<?php
declare (strict_types=1);

namespace app\common\model\store;

use cores\BaseModel;
use think\model\relation\BelongsTo;
use think\model\relation\BelongsToMany;
use think\model\relation\HasOne;

/**
 * 机构用户模型
 * Class User
 * @package app\common\model
 */
class User extends BaseModel
{
    // 定义表名
    protected $name = 'store_user';

    // 定义主键
    protected $pk = 'store_user_id';

    /**
     * 追加字段
     * @var array
     */
    protected $append = ['parentUser'];

    /**
     * 验证用户名是否重复
     * @param string $userName
     * @return bool
     */
    public static function checkExist(string $userName)
    {
        return (bool)static::withoutGlobalScope()
            ->where('user_name', '=', $userName)
            ->where('is_delete', '=', 0)
            ->value('store_user_id');
    }

    /**
     * 验证手机号码是否重复
     * @param string $phone
     * @return bool
     */
    public static function checkPhoneExist(string $phone)
    {
        return (bool)static::withoutGlobalScope()
            ->where('phone', '=', $phone)
            ->where('is_delete', '=', 0)
            ->value('store_user_id');
    }

    /**
     * 机构用户详情
     * @param $where
     * @param array $with
     * @return array|static|null
     */
    public static function detail($where, array $with = [])
    {
        return static::get($where, $with);
    }

    /**
     * 头像
     * @return HasOne
     */
    public function avatarFile()
    {
        return $this->hasOne('app\\store\\model\\UploadFile', 'file_id', 'avatar_file_id');
    }

    /**
     * 关联机构记录表
     * @return BelongsTo
     */
    public function store()
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\Store", 'store_id');
    }

    /**
     * 关联用户角色表表
     * @return BelongsToMany
     */
    public function role()
    {
        return $this->belongsToMany('Role', 'StoreUserRole');
    }

    /**
     * 获取上级渠道
     * @return BelongsToMany
     */
    public function getParentUserAttr($value, $data)
    {
        return static::get($data["parent_store_user_id"]);
    }
}
